<script setup lang="ts">
import {useRoute, useRouter} from 'vue-router'
import {computed, onBeforeMount, onMounted, onUpdated, reactive, ref} from "vue";
import {
  createOrders,
  findAllByUidOrByUidAndBid,
  getBusinessByBusinessId,
  getDeliveryAddressByUserId
} from "../network/api.ts";


const route = useRoute()
const router = useRouter()
let user = ref({
  userId:sessionStorage.getItem("userId"),
  password:"",
  userName:sessionStorage.getItem("userName"),
  userSex:sessionStorage.getItem("userSex"),
  userImg:""
})

let business = ref({  //这里必须使用ref才能响应式赋值字典, 否则会出bug
  businessId:'',
  businessName:'',
  businessAddress:'',
  businessExplain:'',
  bussinessImg:'',
  orderTypeId:1,
  starPrice:0.0,
  deliveryPrice:0.0,
  remarks:'',
  quantity:1
})
let deliveryaddress = ref({
  daId:0,
  contactName:"",
  contactSex:1,
  contactTel:"",
  address:"",
  userId:""
})
let car = reactive({
  cartId:0,
  foodId:0,
  businessId:0,
  userId:"",
  quantity:0,
  food:reactive({
    foodId:0,
    foodName:"",
    foodExplain:"",
    foodImg:"",
    foodPrice:0.0,
    businessId:0,
    remarks:""
  }),
  business:ref(
      {
        businessId:'',
        businessName:'',
        businessAddress:'',
        businessExplain:'',
        bussinessImg:'',
        orderTypeId:1,
        starPrice:0.0,
        deliveryPrice:0.0,
        remarks:'',
        quantity:1
      }
  )
})
let carArr = ref([car])

let bussinessId = route.query.businessId
let userT = sessionStorage.getItem("user")
let userId = sessionStorage.getItem("userId")
let url = "http://localhost:8080"

//  /BusinessController/getBusinessById/
console.log("setup时创建:")


getBusinessByBusinessId(bussinessId).then(res=>{
      business.value = res.data
    }).catch(error=>{
      console.log(error)
})


let data = reactive({
  uid:userId,
  bid:bussinessId
})
findAllByUidOrByUidAndBid(data).then(res=>{
      carArr.value = res.data
      console.log("carArr[0].food.value:")
      console.log(carArr.value[0])
     //这里为什么查不到, 因为你之前的订单 add时, 都没做这个food, business的操作 :), 而且查找(对应的那个service)的订单,返回的cart对象是没有这个food, business对象的
    })
    .catch(error=>{
      console.log(error)
    })

let totalPrice = computed(()=>{
  let totalPrice = 0
  for(let cartItem of carArr.value){
    totalPrice += cartItem.food.foodPrice*cartItem.quantity
    console.log("总价为:"+totalPrice)
  }
  totalPrice += business.value.deliveryPrice
  return totalPrice

})

let userCall = ref()
onMounted(()=> {
  console.log("onMounted：deliveryaddress.value.address = "+deliveryaddress.value.address)
  getDeliveryAddressByUserId(user.value.userId).then(res=>{
    if(res.data.length>0){
      console.log("localStorage.getItem(user.value.userId)=" + localStorage.getItem(user.value.userId))
      deliveryaddress.value.address = localStorage.getItem(user.value.userId)
    }else {
      deliveryaddress.value.address = ''
    }
  })

  if (user.value.userSex == 0) {
    userCall.value = "女士"
  } else {
    userCall.value = "男士"
  }
})

function toUserAddress(){
  router.push({
    path:'/userAddress',
    query:{businessId:business.value.businessId}
  })
}

function toPayment(){
  console.log("点击pay时，deliveryaddress.value.address = "+deliveryaddress.value.address)
  if(deliveryaddress.value.address == ""||deliveryaddress.value.address == null){ //表明处于 地址 初始状态
    alert('请选择送货地址')
    console.log("请选择送货地址")
    return
  }

  createOrders(userId,bussinessId,deliveryaddress.value.daId,totalPrice.value).then(res=>{
        let orderId = res.data.orderId
        if(orderId>0){
          router.push({
            path:'/payment',
            query:{orderId:orderId}
          })
          console.log("orderId = "+orderId)
        }else{
          alert('创建订单失败！')
          console.log("创建订单失败")
        }

      })
      .catch(error=>{
        console.log(error)
      })
}
</script>

<template>
  <div class="wrapper w-full h-full">

    <!-- header部分 -->
    <header class="w-full h-12vw bg-[#0097ff] flex justify-around items-center text-white text-[4.8vw] fixed left-0 top-0 z-1000">
      <p>确认订单</p>
    </header>

    <!-- 订单信息部分 -->
    <div class="order-info w-full mt-12vw bg-#0097ef box-border p-2vw text-white">
      <h5 class="text-3vw font-300">订单配送至：</h5>
      <div class="order-info-address w-full flex justify-between items-center font-700 select-none cursor-pointer mx-1vw my-0 " @click="toUserAddress">
        <div v-if="deliveryaddress.address==''||deliveryaddress.address==null">
          <p class="text-4vw hover:text-blue-2">请选择送货地址</p>
        </div>
        <div v-else>
          <p class="text-4vw">{{ deliveryaddress.address }}</p>
        </div>

<!--        <p class="w-90% text-5vw">{{deliveryaddress.address!=""||deliveryaddress.address!=null?deliveryaddress.address:'请选择送货地址'}}</p>-->
        <svg class="fa-angle-right w-10vw hover:text-blue-2" xmlns="http://www.w3.org/2000/svg"  viewBox="0 0 24 24"><path fill="currentColor" d="M9.172 18.657a1 1 0 0 1-.707-1.707l4.95-4.95l-4.95-4.95a1 1 0 0 1 1.414-1.414l5.656 5.657a1 1 0 0 1 0 1.414L9.88 18.364a.997.997 0 0 1-.707.293Z"/></svg>
      </div>
      <p class="text-3vw">{{user.userName}}{{userCall}} {{user.userId}}</p>
    </div>

    <h3 class="box-border p-3vw text-4vw text-#666 border-b-1px border-solid border-#ddd">{{business.businessName}}</h3>

    <!-- 订单明细部分 -->
    <ul class="order-detailed w-full ">
      <li class="w-full h-16vw box-border p-3vw text-#666 flex justify-between items-center"
          v-for="item in carArr"
      >
        <div class="order-detailed-left flex items-center">
          <img :src="item.food?.foodImg" class="w-10vw h-10vw">
          <p class="text-3.5vw ml-3vw">{{item.food.foodName}} x {{item.quantity}}</p>
        </div>
        <p class="text-3.5vw">&#165;{{item.food.foodPrice*item.quantity}}</p>
      </li>
    </ul>
    <div class="order-deliveryfee w-full h-16vw box-border p-3vw text-#666 flex justify-between items-center text-3.5vw">
      <p>配送费</p>
      <p>&#165;{{business.deliveryPrice}}</p>
    </div>

    <!-- 合计部分 -->
    <div class="total w-full h-14vw fixed left-0 bottom-0 flex">
      <div class="total-left flex w-70% bg-#505051 text-white text-4.5vw font-700 select-none justify-center items-center">
        &#165;{{totalPrice}}
      </div>
      <div class="total-right flex w-20vw grow bg-#38ca73 text-white text-4.5vw font-700 select-none cursor-pointer justify-center items-center" @click="toPayment">
        去支付
      </div>
    </div>
  </div>
</template>

<style scoped>

</style>